import 'package:flutter/material.dart';
import 'services/websocket_service.dart';
import 'services/storage_service.dart';
import 'services/activation_service.dart';
import 'services/activation_dialog.dart';
import 'dart:io'; 
import 'dart:async';
import 'package:printing/printing.dart'; 
import 'services/ios_printer_service.dart';

void main() {
  runApp(MyApp());
}

// 修改 main.dart
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: '抖音弹幕解析',
        theme: ThemeData(
          primarySwatch: Colors.deepPurple,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          fontFamily: 'MiSans',
        ),
        home: ActivationWrapper(),
        debugShowCheckedModeBanner: false,
      );
    }
  }

  class ActivationWrapper extends StatefulWidget {
    @override
    _ActivationWrapperState createState() => _ActivationWrapperState();
  }

  class _ActivationWrapperState extends State<ActivationWrapper> {
    final ActivationService _activationService = ActivationService();
    bool _isChecking = true;
    bool _isActivated = false;

    @override
    void initState() {
      super.initState();
      _checkActivationOnStart();
    }

    Future<void> _checkActivationOnStart() async {
      // 首先尝试从本地加载激活状态
      final hasValidActivation = await _activationService.loadActivationFromStorage();
      
      if (hasValidActivation) {
        setState(() {
          _isActivated = true;
          _isChecking = false;
        });
      } else {
        // 如果没有有效激活，显示激活对话框
        final activated = await ActivationDialog.show(
          context: context,
          maxAttempts: 3,
        );
        
        setState(() {
          _isActivated = activated;
          _isChecking = false;
        });
        
        if (!activated) {
          // 激活失败，退出应用
          Future.delayed(Duration.zero, () => exit(0));
        }
      }
    }

    @override
    Widget build(BuildContext context) {
      if (_isChecking) {
        return _buildLoadingScreen();
      }
      
      if (!_isActivated) {
        return _buildActivationFailedScreen();
      }
      
      return ConnectionPage();
    }

    Widget _buildLoadingScreen() {
      return Scaffold(
        backgroundColor: Colors.grey[50],
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.deepPurple),
              ),
              SizedBox(height: 16),
              Text(
                '检查激活状态...',
                style: TextStyle(fontSize: 16, color: Colors.grey),
              ),
            ],
          ),
        ),
      );
    }

    Widget _buildActivationFailedScreen() {
      return Scaffold(
        backgroundColor: Colors.grey[50],
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.red,
              ),
              SizedBox(height: 16),
              Text(
                '激活验证失败',
                style: TextStyle(fontSize: 18, color: Colors.red),
              ),
              SizedBox(height: 8),
              Text(
                '请重新启动应用并输入有效的激活码',
                style: TextStyle(color: Colors.grey),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    }

    @override
    void dispose() {
      _activationService.dispose();
      super.dispose();
    }

  }

  class ConnectionPage extends StatefulWidget {
    @override
    _ConnectionPageState createState() => _ConnectionPageState();
  }

  class _ConnectionPageState extends State<ConnectionPage> with SingleTickerProviderStateMixin {
    final TextEditingController _roomIdController = TextEditingController();
    final TextEditingController _keywordController = TextEditingController();
    late ScrollController _scrollController;
    final DouyinWebSocketService _webSocketService = DouyinWebSocketService();
    final StorageService _storageService = StorageService();
    final ActivationService _activationService = ActivationService();
    bool _exactMatch = false; // 精准匹配开关
    // 打印机相关变量
    final PrinterService _printerManager = createPrinterService();
    bool _autoPrint = false;
    bool _isPrinterConnected = false;
    List<Printer> _availablePrinters = [];
    Printer? _selectedPrinter;

    List<LiveMessage> _messages = [];
    bool _isConnected = false;
    List<String> _keywords = [];
    bool _isLoading = false;
    
    late AnimationController _animationController;
    late Animation<double> _fadeAnimation;
    late Animation<Offset> _slideAnimation;

    @override
    void initState() {
      super.initState();
      _scrollController = ScrollController();
      _initializeAnimations();
      _loadSavedData();
      _setupWebSocketListeners();
      _setupPrinterListeners();
      _startActivationCheck(); // 添加激活状态检查
      _initializePrinter();
    }

  // 初始化打印机
  void _initializePrinter() async {
    await _printerManager.initialize();
    // 初始化后立即更新连接状态
    if (mounted) {
      setState(() {
        _isPrinterConnected = _printerManager.isConnected;
      });
    }
    await _loadPrinterSettings();
  }

  // 设置打印机监听器
  void _setupPrinterListeners() {
    _printerManager.onConnectionChanged = (connected) {
      if (mounted) {
        setState(() {
          _isPrinterConnected = connected;
        });
      }
    };

    _printerManager.onError = (error) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('打印机错误: $error'),
            backgroundColor: Colors.red,
            duration: Duration(seconds: 3),
          ),
        );
      }
    };
  }

  // 加载打印机设置
  Future<void> _loadPrinterSettings() async {
    final savedAutoPrint = await _storageService.loadAutoPrint();
    
    if (mounted) {
      setState(() {
        _autoPrint = savedAutoPrint;
      });
    }
  }

  // 添加自动滚动到顶部的方法
  void _scrollToTop() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  // 定期检查激活状态
  void _startActivationCheck() {
    Timer.periodic(Duration(minutes: 1), (timer) {
      if (_activationService.isExpired && mounted) {
        timer.cancel();
        _showActivationExpiredDialog();
      }
    });
  }

  void _showActivationExpiredDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.warning, color: Colors.orange),
            SizedBox(width: 8),
            Text('激活已过期'),
          ],
        ),
        content: Text('您的软件激活已过期，部分功能将受限。请重新激活以继续使用完整功能。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('知道了'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _showReactivationDialog();
            },
            child: Text('重新激活'),
          ),
        ],
      ),
    );
  }

    void _showReactivationDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('重新激活'),
        content: Text('是否现在重新激活软件？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              final activated = await ActivationDialog.show(
                context: context,
                maxAttempts: 3,
              );
              if (activated) {
                setState(() {}); // 刷新界面
              }
            },
            child: Text('重新激活'),
          ),
        ],
      ),
    );
  }

  // 添加滚动到底部的方法（如果需要）
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        0.0,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  void _initializeAnimations() {
    _animationController = AnimationController(
      duration: Duration(milliseconds: 500),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeIn),
    );
    
    _slideAnimation = Tween<Offset>(
      begin: Offset(0, 0.1),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _animationController, curve: Curves.easeOut));
    
    _animationController.forward();
  }

  Future<void> _loadSavedData() async {
    setState(() => _isLoading = true);
    
    final savedRoomId = await _storageService.loadLastRoomId();
    final savedKeywords = await _storageService.loadKeywords();
    final savedMessages = await _storageService.loadMessages();
    final savedExactMatch = await _storageService.loadExactMatch();

    if (mounted) {
      setState(() {
        if (savedRoomId != null) _roomIdController.text = savedRoomId;
        _keywords = savedKeywords;
        _keywordController.text = savedKeywords.join('#');
        _messages = savedMessages.map((msg) => LiveMessage.fromJson(msg)).toList();
        _exactMatch = savedExactMatch;
        _isLoading = false;
      });
    }
  }

  void _setupWebSocketListeners() {
    _webSocketService.onConnectionChanged = (connected) {
      if (mounted) {
        setState(() {
          _isConnected = connected;
        });
      }
    };

    _webSocketService.onMessageReceived = (messageData) {
      if (mounted) {
        setState(() {
           try {
              final message = LiveMessage.fromJson(messageData);
              _messages.add(message);
              _saveMessages();
        
              // 检查是否需要打印
              _checkAndPrintMessage(message);

              WidgetsBinding.instance.addPostFrameCallback((_) {
                _scrollToTop();
              });
            } catch (e) {
              print('处理消息错误: $e, 消息数据: $messageData');
            }
        });
      }
    };


    _webSocketService.onError = (error) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('错误: $error'),
          backgroundColor: Colors.red,
          duration: Duration(seconds: 3),
        ),
      );
    };
  }

  Future<void> _saveMessages() async {
    final messagesJson = _messages.map((msg) => msg.toJson()).toList();
    await _storageService.saveMessages(messagesJson);
  }

  void _checkAndPrintMessage(LiveMessage message) {
    if (_autoPrint && _isPrinterConnected && _shouldPrintMessage(message)) {
      // 使用正确的参数调用
      _printerManager.printSimpleChatMessage(
        message.user.name,
        message.content,
        message.user.shortId,
      );
    }
  }

    // 判断消息是否需要打印（基于关键词过滤）
  bool _shouldPrintMessage(LiveMessage message) {
    if (_keywords.isEmpty) {
      return true; // 没有关键词时打印所有消息
    }
    
    return _keywords.any((keyword) {
      if (_exactMatch) {
        return message.content == keyword;
      } else {
        return message.content.toLowerCase().contains(keyword.toLowerCase());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: Text('抖音弹幕助手'),
        backgroundColor: Colors.deepPurple,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          // 激活状态菜单
          _buildActivationMenu(),
        ],
      ),
      body: SingleChildScrollView(  // 添加滚动功能
        child: ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: MediaQuery.of(context).size.height,
          ),
          child: _isLoading ? _buildLoadingScreen() : _buildMainScreen(),
        ),
      ),
    );
  }

  // 添加激活状态菜单
Widget _buildActivationMenu() {
  return PopupMenuButton<String>(
    icon: Icon(
      _activationService.isActivated ? Icons.verified : Icons.error_outline,
      color: _activationService.statusColor,
    ),
    onSelected: (value) {
      if (value == 'activate') {
        _showReactivationDialog();
      } else if (value == 'status') {
        _showActivationDetails();
      }
    },
    itemBuilder: (BuildContext context) => [
      PopupMenuItem<String>(
        value: 'status',
        child: Row(
          children: [
            Icon(Icons.info, color: Colors.blue),
            SizedBox(width: 8),
            Text('激活状态'),
          ],
        ),
      ),
      PopupMenuItem<String>(
        value: 'activate',
        child: Row(
          children: [
            Icon(Icons.vpn_key, color: Colors.green),
            SizedBox(width: 8),
            Text('重新激活'),
          ],
        ),
      ),
    ],
  );
}

// 显示激活详情
void _showActivationDetails() {
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Row(
        children: [
          Icon(Icons.verified, color: _activationService.statusColor),
          SizedBox(width: 8),
          Text('激活状态详情'),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildActivationDetailRow('状态', _activationService.detailedStatusText),
          if (_activationService.isActivated && _activationService.expireTime != null)
            _buildActivationDetailRow(
              '到期时间', 
              _activationService.expireTime!.toString().split(' ')[0]
            ),
          if (_activationService.isActivated)
            _buildActivationDetailRow('激活码', '••••${_activationService.activationCode.substring(_activationService.activationCode.length - 4)}'),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: Text('关闭'),
        ),
        if (!_activationService.isActivated || _activationService.isExpired)
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _showReactivationDialog();
            },
            child: Text('激活'),
          ),
      ],
    ),
  );
}

Widget _buildActivationDetailRow(String label, String value) {
  return Padding(
    padding: EdgeInsets.symmetric(vertical: 8),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: 80,
          child: Text(
            '$label:',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade600,
            ),
          ),
        ),
        SizedBox(width: 8),
        Expanded(
          child: Text(
            value,
            style: TextStyle(
              color: Colors.grey.shade800,
            ),
          ),
        ),
      ],
    ),
  );
}

  Widget _buildLoadingScreen() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.deepPurple),
          ),
          SizedBox(height: 16),
          Text(
            '加载中...',
            style: TextStyle(fontSize: 16, color: Colors.grey),
          ),
        ],
      ),
    );
  }

  Widget _buildMainScreen() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: SlideTransition(
        position: _slideAnimation,
        child: Column(
          children: [
            // 状态栏
            _buildStatusBar(),
            
            // 输入区域
            _buildInputSection(),
            
            // 消息列表
            Container(
              height: MediaQuery.of(context).size.height * 0.5, // 设置合适的高度
              child: _buildMessageList(),
            ),
          ],
        ),
      ),
    );
  }

  // 修改状态栏显示
  Widget _buildStatusBar() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: _isConnected 
              ? [Colors.green.shade100, Colors.green.shade50]
              : [Colors.red.shade100, Colors.red.shade50],
        ),
      ),
      child: Row(
        children: [
          // 连接状态指示器
          AnimatedContainer(
            duration: Duration(milliseconds: 300),
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: _isConnected ? Colors.green : Colors.red,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: _isConnected ? Colors.green : Colors.red,
                  blurRadius: 6,
                  spreadRadius: _isConnected ? 1 : 0,
                ),
              ],
            ),
          ),
          SizedBox(width: 8),
          
          // 激活状态指示器
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: _activationService.statusColor,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: _activationService.statusColor.withOpacity(0.5),
                  blurRadius: 3,
                  spreadRadius: 1,
                ),
              ],
            ),
          ),
          SizedBox(width: 6),
          
          // 激活状态文本
          Container(
            padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
            decoration: BoxDecoration(
              color: _activationService.statusColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: _activationService.statusColor),
            ),
            child: Text(
              _activationService.shortStatusText,
              style: TextStyle(
                color: _activationService.statusColor,
                fontSize: 9,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(width: 8),
          
            // 打印机状态指示器
          Container(
            width: 10,
            height: 10,
            decoration: BoxDecoration(
              color: _isPrinterConnected ? Colors.green : Colors.grey,
              shape: BoxShape.circle,
            ),
          ),
          SizedBox(width: 6),

          // 打印机状态文本
          Container(
            padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
            decoration: BoxDecoration(
              color: _isPrinterConnected ? Colors.green.shade100 : Colors.grey.shade100,
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: _isPrinterConnected ? Colors.green : Colors.grey),
            ),
            child: Text(
              _isPrinterConnected ? '打印机' : '无打印',
              style: TextStyle(
                color: _isPrinterConnected ? Colors.green.shade800 : Colors.grey.shade800,
                fontSize: 9,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(width: 8),

          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _isConnected ? '已连接到直播间' : '未连接',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: _isConnected ? Colors.green.shade800 : Colors.red.shade800,
                    fontSize: 13,
                  ),
                ),
                Text(
                  '消息数量: ${_messages.length}',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
          
          if (_isConnected) _buildPulseIndicator(),
        ],
      ),
    );
  }

  Widget _buildPulseIndicator() {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: 0.0, end: 1.0),
      duration: Duration(seconds: 2),
      builder: (context, value, child) {
        return Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(
            color: Colors.green.withOpacity(1 - value),
            shape: BoxShape.circle,
          ),
        );
      },
    );
  }

  Widget _buildInputSection() {
    return Column(
      children: [
        // 激活状态卡片
        _buildActivationStatusCard(),
        SizedBox(height: 8),
        
              // 打印机控制卡片
        _buildPrinterControlCard(),
        SizedBox(height: 8),

        Card(
          margin: EdgeInsets.all(10),
          elevation: 4,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Column(
              children: [
                // 房间ID输入
                _buildInputField(
                  controller: _roomIdController,
                  label: '直播间ID',
                  hint: '输入抖音直播间ID',
                  icon: Icons.live_tv,
                ),
                SizedBox(height: 10),
                
                // 关键词输入
                _buildInputField(
                  controller: _keywordController,
                  label: '关键词过滤',
                  hint: '多个关键词用#分隔',
                  icon: Icons.filter_list,
                ),
                SizedBox(height: 10),

                // 精准匹配开关
                _buildExactMatchSwitch(),
                SizedBox(height: 10),

                // 按钮组
                _buildButtonGroup(),
              ],
            ),
          ),
        ),
      ],
    );
  }

    Widget _buildPrinterControlCard() {
    return Card(
      margin: EdgeInsets.symmetric(horizontal: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Container(
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: [
              _isPrinterConnected ? Colors.green.shade100 : Colors.red.shade100,
              _isPrinterConnected ? Colors.green.shade50 : Colors.red.shade50,
            ],
          ),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Icon(
                  _isPrinterConnected ? Icons.print : Icons.print_disabled,
                  color: _isPrinterConnected ? Colors.green : Colors.red,
                  size: 20,
                ),
                SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'AirPrint 打印机',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: Colors.grey.shade700,
                          fontSize: 14,
                        ),
                      ),
                      Text(
                        _isPrinterConnected 
                            ? '设备支持打印功能' 
                            : '设备不支持打印或未设置',
                        style: TextStyle(
                          fontSize: 11,
                          color: _isPrinterConnected ? Colors.green.shade700 : Colors.red.shade700,
                        ),
                      ),
                    ],
                  ),
                ),
                PopupMenuButton<String>(
                  onSelected: (value) {
                    if (value == 'scan') {
                      _scanPrinters();
                    } else if (value == 'test') {
                      _testPrint();
                    } else if (value == 'settings') {
                      _showPrinterSettings();
                    }
                  },
                  itemBuilder: (BuildContext context) => [
                    PopupMenuItem<String>(
                      value: 'scan',
                      child: Row(
                        children: [
                          Icon(Icons.search, color: Colors.blue),
                          SizedBox(width: 8),
                          Text('查找打印机'),
                        ],
                      ),
                    ),
                    PopupMenuItem<String>(
                      value: 'test',
                      child: Row(
                        children: [
                          Icon(Icons.print, color: Colors.green),
                          SizedBox(width: 8),
                          Text('测试打印'),
                        ],
                      ),
                    ),
                    PopupMenuItem<String>(
                      value: 'settings',
                      child: Row(
                        children: [
                          Icon(Icons.settings, color: Colors.orange),
                          SizedBox(width: 8),
                          Text('打印设置'),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
            SizedBox(height: 8),
            Row(
              children: [
                Icon(Icons.autorenew, color: Colors.blue, size: 20),
                SizedBox(width: 6),
                Text(
                  '自动打印聊天消息',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.grey.shade700,
                    fontSize: 13,
                  ),
                ),
                Spacer(),
                Switch(
                  value: _autoPrint,
                  onChanged: (value) {
                    setState(() {
                      _autoPrint = value;
                    });
                    _storageService.saveAutoPrint(value);
                    if (value && !_isPrinterConnected) {
                      _showSnackBar('请先确保设备支持打印功能', Colors.orange);
                    } else if (value) {
                      _showSnackBar('已启用自动打印', Colors.green);
                    } else {
                      _showSnackBar('已关闭自动打印', Colors.grey);
                    }
                  },
                  activeColor: Colors.deepPurple,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 显示打印设置
  void _showPrinterSettings() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('打印设置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('iOS打印说明：', style: TextStyle(fontWeight: FontWeight.bold)),
            SizedBox(height: 8),
            Text('• 确保设备连接到与打印机相同的WiFi网络'),
            Text('• 支持所有AirPrint兼容的打印机'),
            Text('• 自动打印功能需要保持App在前台运行'),
            SizedBox(height: 16),
            Text('当前状态: ${_isPrinterConnected ? '已连接' : '未连接'}'),
            if (_printerManager.printerName != null)
              Text('打印机: ${_printerManager.printerName}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _scanPrinters();
            },
            child: Text('重新扫描'),
          ),
        ],
      ),
    );
  }
  // 扫描打印机
  void _scanPrinters() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final printers = await _printerManager.findPrinters();
      setState(() {
        _availablePrinters = printers;
      });
      
      if (printers.isEmpty) {
        _showSnackBar('未找到可用的打印机', Colors.orange);
      } else {
        _showPrinterSelectionDialog(printers);
      }
    } catch (e) {
      _showSnackBar('扫描打印机失败: $e', Colors.red);
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 显示打印机选择对话框
  void _showPrinterSelectionDialog(List<Printer> printers) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('选择打印机'),
        content: Container(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: printers.length,
            itemBuilder: (context, index) {
              final printer = printers[index];
              return ListTile(
                leading: Icon(Icons.print),
                title: Text(printer.name ?? '未知设备'),
                subtitle: Text(printer.url?.toString() ?? printer.name ?? ''),
                onTap: () async {
                  Navigator.of(context).pop();
                  await _connectToPrinter(printer);
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
        ],
      ),
    );
  }

  // 连接到打印机
  Future<void> _connectToPrinter(Printer printer) async {
    setState(() {
      _isLoading = true;
    });

    final success = await _printerManager.connect(printer);
    
    if (success) {
      // 保存打印机设备信息
      await _storageService.savePrinterDevice({
        'name': printer.name,
        'url': printer.url?.toString(),
      });
      _showSnackBar('已连接到打印机: ${printer.name}', Colors.green);
    } else {
      _showSnackBar('连接打印机失败', Colors.red);
    }

    setState(() {
      _isLoading = false;
    });
  }

  // 测试打印
  void _testPrint() async {
    if (!_isPrinterConnected) {
      _showSnackBar('请先连接打印机', Colors.orange);
      return;
    }

    final success = await _printerManager.printText(
      '这是抖音弹幕打印测试\n测试时间: ${DateTime.now().toString().split('.').first}',
    );
    
    if (success) {
      _showSnackBar('测试打印已发送', Colors.green);
    } else {
      _showSnackBar('测试打印失败', Colors.red);
    }
  }

  Widget _buildExactMatchSwitch() {
    return Row(
      children: [
        Icon(Icons.check_circle_outline, color: Colors.grey.shade600, size: 20),
        SizedBox(width: 8),
        Text(
          '精准匹配',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey.shade700,
          ),
        ),
        Spacer(),
        Switch(
          value: _exactMatch,
          onChanged: (value) {
            setState(() {
              _exactMatch = value;
            });
            // 自动保存设置
            _storageService.saveExactMatch(value);
            if (_keywords.isNotEmpty) {
              _showSnackBar(
                value ? '已开启精准匹配' : '已关闭精准匹配', 
                Colors.blue
              );
              // 刷新过滤结果
              setState(() {});
            }
          },
          activeColor: Colors.deepPurple,
        ),
      ],
    );
  }

// 添加激活状态卡片
Widget _buildActivationStatusCard() {
  return Card(
    margin: EdgeInsets.symmetric(horizontal: 12),
    elevation: 2,
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
    child: Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            _activationService.statusColor.withOpacity(0.1),
            _activationService.statusColor.withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: _activationService.statusColor.withOpacity(0.3),
        ),
      ),
      child: Row(
        children: [
          Icon(
            _activationService.isActivated ? Icons.verified : Icons.error_outline,
            color: _activationService.statusColor,
            size: 20,
          ),
          SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '软件激活状态',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.grey.shade700,
                    fontSize: 14,
                  ),
                ),
                SizedBox(height: 2),
                Text(
                  _activationService.detailedStatusText,
                  style: TextStyle(
                    fontSize: 11,
                    color: _activationService.statusColor,
                  ),
                ),
                if (_activationService.shouldShowWarning) ...[
                  SizedBox(height: 6),
                  LinearProgressIndicator(
                    value: _activationService.remainingPercentage,
                    backgroundColor: Colors.grey.shade300,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      _activationService.statusColor,
                    ),
                  ),
                ],
              ],
            ),
          ),
          if (_activationService.shouldShowWarning)
            IconButton(
              onPressed: _showReactivationDialog,
              icon: Icon(Icons.autorenew, color: _activationService.statusColor, size: 20),
              padding: EdgeInsets.all(4), // 减小内边距
              constraints: BoxConstraints(minWidth: 36, minHeight: 36), // 减小约束
              tooltip: '重新激活',
            ),
        ],
      ),
    ),
  );
}

Widget _buildInputField({
    required TextEditingController controller,
    required String label,
    required String hint,
    required IconData icon,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey.shade700,
          ),
        ),
        SizedBox(height: 6),
        Container(
          decoration: BoxDecoration(
            color: Colors.grey.shade50,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: TextField(
            controller: controller,
            decoration: InputDecoration(
              hintText: hint,
              border: InputBorder.none,
              prefixIcon: Icon(icon, color: Colors.grey.shade500),
              contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 14),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildButtonGroup() {
    return Row(
      children: [
        Expanded(
          child: AnimatedContainer(
            duration: Duration(milliseconds: 300),
            child: ElevatedButton(
              onPressed: _isConnected ? _disconnect : _connect,
              style: ElevatedButton.styleFrom(
                backgroundColor: _isConnected ? Colors.red : Colors.green,
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                elevation: 2,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(_isConnected ? Icons.stop : Icons.play_arrow),
                  SizedBox(width: 8),
                  Text(_isConnected ? '断开连接' : '开始连接'),
                ],
              ),
            ),
          ),
        ),
        SizedBox(width: 12),
        _buildIconButton(
          icon: Icons.save,
          onPressed: _saveKeywords,
          tooltip: '保存关键词',
        ),
        SizedBox(width: 8),
        _buildIconButton(
          icon: Icons.clear_all,
          onPressed: _clearMessages,
          tooltip: '清空消息',
        ),
      ],
    );
  }

  Widget _buildIconButton({
    required IconData icon,
    required VoidCallback onPressed,
    required String tooltip,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: Colors.blue.shade100),
      ),
      child: IconButton(
        onPressed: onPressed,
        icon: Icon(icon, color: Colors.blue.shade600, size: 20),
        tooltip: tooltip,
        padding: EdgeInsets.all(8),
      ),
    );
  }

  // 在 _buildMessageList 方法中添加浮动按钮
  Widget _buildMessageList() {
    final filteredMessages = _filterMessages();
    
    return Stack(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(12, 0, 12, 12),
          child: Card(
            elevation: 4,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
            child: Column(
              children: [
                // 列表标题
                _buildListHeader(filteredMessages.length),
                
                // 消息列表
                Expanded(
                  child: filteredMessages.isEmpty
                      ? _buildEmptyState()
                      : _buildMessageListView(filteredMessages),
                ),
              ],
            ),
          ),
        ),
        
        // 滚动到顶部按钮
        if (filteredMessages.isNotEmpty)
          Positioned(
            bottom: 16,
            right: 24,
            child: FloatingActionButton.small(
              onPressed: _scrollToTop,
              backgroundColor: Colors.deepPurple,
              foregroundColor: Colors.white,
              child: Icon(Icons.arrow_upward, size: 18),
              tooltip: '滚动到最新消息',
            ),
          ),
      ],
    );
  }

  // 更新 _buildListHeader 方法
  Widget _buildListHeader(int filteredCount) {
    final hasKeywords = _keywords.isNotEmpty;
    
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.deepPurple.shade50,
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      child: Row(
        children: [
          Icon(Icons.chat, color: Colors.deepPurple, size: 20),
          SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '实时弹幕',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.deepPurple.shade800,
                    fontSize: 14,
                  ),
                ),
                if (hasKeywords)
                  Text(
                    '关键词过滤: ${_keywords.join(", ")} ${_exactMatch ? '(精准匹配)' : '(模糊匹配)'}',
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.deepPurple.shade600,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
              ],
            ),
          ),
          SizedBox(width: 6),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
            decoration: BoxDecoration(
              color: hasKeywords ? Colors.orange : Colors.deepPurple,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              '$filteredCount',
              style: TextStyle(
                color: Colors.white,
                fontSize: 11,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          SizedBox(width: 6),
          Text(
            '总计: ${_messages.length}',
            style: TextStyle(
              color: Colors.deepPurple.shade600,
              fontSize: 11,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.chat_bubble_outline,
            size: 64,
            color: Colors.grey.shade300,
          ),
          SizedBox(height: 16),
          Text(
            '暂无消息',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey.shade500,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 8),
          Text(
            _isConnected ? '等待接收消息...' : '请先连接直播间',
            style: TextStyle(color: Colors.grey.shade400),
          ),
          if (_keywords.isNotEmpty)
            Padding(
              padding: EdgeInsets.only(top: 8),
              child: Column(
              children: [
                Text(
                  '当前有关键词过滤: ${_keywords.join(", ")}',
                  style: TextStyle(
                    color: Colors.orange.shade600,
                    fontSize: 12,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 4),
                Text(
                  '匹配模式: ${_exactMatch ? '精准匹配' : '模糊匹配'}',
                  style: TextStyle(
                    color: Colors.blue.shade600,
                    fontSize: 11,
                  ),
                ),
              ],
              ),
          ),
        ],
      ),
    );
  }

  Widget _buildMessageListView(List<LiveMessage> messages) {
    return ListView.builder(
      controller: _scrollController,
      reverse: true,
      itemCount: messages.length,
      padding: EdgeInsets.all(8),
      itemBuilder: (context, index) {
        return _buildAnimatedMessageItem(messages[index]);
      },
    );
  }

  Widget _buildAnimatedMessageItem(LiveMessage message) {
    return Dismissible(
      key: ValueKey(message.id),
      direction: DismissDirection.endToStart,
      background: Container(
        color: Colors.red.shade100,
        alignment: Alignment.centerRight,
        padding: EdgeInsets.only(right: 20),
        child: Icon(Icons.delete, color: Colors.red),
      ),
      onDismissed: (direction) {
        setState(() {
          _messages.removeWhere((m) => m.id == message.id);
          _saveMessages();
        });
      },
      child: _buildMessageItem(message),
    );
  }

  Widget _buildMessageItem(LiveMessage message) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 3),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _showMessageDetails(message),
          borderRadius: BorderRadius.circular(12),
          child: Container(
            padding: EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 3,
                  offset: Offset(0, 1),
                ),
              ],
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 用户头像
                _buildUserAvatar(message),
                SizedBox(width: 10),
                
                // 消息内容
                Expanded(child: _buildMessageContent(message)),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUserAvatar(LiveMessage message) {
    return Stack(
      children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: _getUserGradient(message.user.id),
            ),
            shape: BoxShape.circle,
          ),
          child: Center(
            child: Text(
              message.user.name.substring(0, 1),
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ),
        ),
        Positioned(
          right: 0,
          bottom: 0,
          child: Container(
            width: 12,
            height: 12,
            decoration: BoxDecoration(
              color: _getMessageTypeColor(message.type),
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 2),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildMessageContent(LiveMessage message) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              message.user.name,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: _getUserColor(message.user.id),
              ),
            ),
            SizedBox(width: 8),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: _getMessageTypeColor(message.type).withOpacity(0.1),
                borderRadius: BorderRadius.circular(4),
                border: Border.all(color: _getMessageTypeColor(message.type)),
              ),
              child: Text(
                _getMessageTypeText(message.type),
                style: TextStyle(
                  color: _getMessageTypeColor(message.type),
                  fontSize: 10,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Spacer(),
            Text(
              _formatTime(message.timestamp),
              style: TextStyle(
                color: Colors.grey.shade500,
                fontSize: 11,
              ),
            ),
          ],
        ),
        SizedBox(height: 6),
        Text(
          message.content,
          style: TextStyle(
            fontSize: 14,
            height: 1.4,
          ),
        ),
      ],
    );
  }

  List<Color> _getUserGradient(String userId) {
    final gradients = [
      [Colors.blue.shade600, Colors.blue.shade400],
      [Colors.green.shade600, Colors.green.shade400],
      [Colors.orange.shade600, Colors.orange.shade400],
      [Colors.purple.shade600, Colors.purple.shade400],
      [Colors.red.shade600, Colors.red.shade400],
      [Colors.teal.shade600, Colors.teal.shade400],
    ];
    final index = userId.hashCode % gradients.length;
    return gradients[index].cast<Color>();
  }

  Color _getUserColor(String userId) {
    final colors = [
      Colors.blue.shade700,
      Colors.green.shade700,
      Colors.orange.shade700,
      Colors.purple.shade700,
      Colors.red.shade700,
      Colors.teal.shade700,
    ];
    final index = userId.hashCode % colors.length;
    return colors[index];
  }

  Color _getMessageTypeColor(MessageType type) {
    switch (type) {
      case MessageType.chat:
        return Colors.blue.shade600;
      case MessageType.gift:
        return Colors.orange.shade600;
      case MessageType.like:
        return Colors.pink.shade600;
      case MessageType.member:
        return Colors.green.shade600;
      case MessageType.social:
        return Colors.purple.shade600;
    }
  }

  String _getMessageTypeText(MessageType type) {
    switch (type) {
      case MessageType.chat:
        return '聊天';
      case MessageType.gift:
        return '礼物';
      case MessageType.like:
        return '点赞';
      case MessageType.member:
        return '进场';
      case MessageType.social:
        return '关注';
    }
  }

  String _formatTime(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);
    
    if (difference.inSeconds < 60) {
      return '刚刚';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}';
    }
  }

  List<LiveMessage> _filterMessages() {
    if (_keywords.isEmpty) {
      return _messages;
    }
    
    return _messages.where((message) {
      return _keywords.any((keyword) {
        if (_exactMatch) {
          // 精准匹配：消息内容必须完全等于关键词
          return message.content == keyword;
        } else {
          // 模糊匹配：消息内容包含关键词
          return message.content.toLowerCase().contains(keyword.toLowerCase());
        }
      });
    }).toList();
  }

  Future<void> _connect() async {
    final roomId = _roomIdController.text.trim();
    if (roomId.isEmpty) {
      _showSnackBar('请输入直播间ID', Colors.orange);
      return;
    }

    setState(() => _isLoading = true);

    final success = await _webSocketService.connect(roomId);
    
    if (success) {
      await _storageService.saveLastRoomId(roomId);
      _showSnackBar('连接成功', Colors.green);
      // 连接成功时确保滚动到顶部
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToTop();
      });
    } else {
      _showSnackBar('连接失败', Colors.red);
    }

    setState(() => _isLoading = false);
  }

  void _disconnect() {
    _webSocketService.disconnect();
    _showSnackBar('已断开连接', Colors.grey);
  }

  Future<void> _saveKeywords() async {
    final keywordsText = _keywordController.text.trim();
    if (keywordsText.isNotEmpty) {
      setState(() {
        _keywords = keywordsText.split('#')
            .map((k) => k.trim())
            .where((k) => k.isNotEmpty)
            .toList();
      });
      await _storageService.saveKeywords(_keywords);
      await _storageService.saveExactMatch(_exactMatch); // 新增
      _showSnackBar('已保存 ${_keywords.length} 个关键词${_exactMatch ? ' (精准匹配)' : ''}', Colors.green);
      
      // 强制刷新界面显示过滤结果
      setState(() {});
    } else {
      setState(() {
        _keywords = [];
      });
      await _storageService.saveKeywords(_keywords);
      await _storageService.saveExactMatch(_exactMatch); // 新增
      _showSnackBar('已清空关键词', Colors.green);
    }
  }

  Future<void> _clearMessages() async {
    if (_messages.isEmpty) return;
    
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认清空'),
        content: Text('确定要清空所有 ${_messages.length} 条消息吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text('清空', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      setState(() {
        _messages.clear();
      });
      await _storageService.clearMessages();
      _showSnackBar('已清空所有消息', Colors.green);
    }
  }

  void _showMessageDetails(LiveMessage message) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许更大高度
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Container(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey.shade300,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
            ),
            SizedBox(height: 20),
            Text(
              '消息详情',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            
            // 用户信息区域
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '用户信息',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(height: 8),
                  _buildDetailRow('用户昵称', message.user.name),
                  if (message.user.shortId.isNotEmpty)
                    _buildDetailRowWithCopy('抖音号', message.user.shortId),
                ],
              ),
            ),
            
            SizedBox(height: 16),
            
            // 消息信息区域
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '消息内容',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(height: 8),
                  _buildDetailRow('内容', message.content),
                  _buildDetailRow('类型', _getMessageTypeText(message.type)),
                  _buildDetailRow('时间', _formatDetailedTime(message.timestamp)),
                ],
              ),
            ),
            
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(),
              style: ElevatedButton.styleFrom(
                minimumSize: Size(double.infinity, 48),
              ),
              child: Text('关闭'),
            ),
            SizedBox(height: MediaQuery.of(context).viewInsets.bottom), // 避免键盘遮挡
          ],
        ),
      ),
    );
  }

  // 添加带复制按钮的详情行
  Widget _buildDetailRowWithCopy(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade600,
                fontSize: 14,
              ),
            ),
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
              ),
              softWrap: true,
            ),
          ),
          SizedBox(width: 8),
          IconButton(
            onPressed: () => _copyToClipboard(value),
            icon: Icon(Icons.content_copy, size: 18),
            padding: EdgeInsets.all(4),
            constraints: BoxConstraints(),
            tooltip: '复制抖音号',
          ),
        ],
      ),
    );
  }

  // 更新 _buildDetailRow 方法
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade600,
                fontSize: 14,
              ),
            ),
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
              ),
              softWrap: true,
            ),
          ),
        ],
      ),
    );
  }

  String _formatDetailedTime(DateTime timestamp) {
    return '${timestamp.year}-${timestamp.month.toString().padLeft(2, '0')}-${timestamp.day.toString().padLeft(2, '0')} ${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}:${timestamp.second.toString().padLeft(2, '0')}';
  }

  // 简化复制方法
  void _copyToClipboard(String text) {
    // 这里可以实现复制到剪贴板功能
    _showSnackBar('已复制: $text', Colors.green);
  }

  void _showSnackBar(String message, Color backgroundColor) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: backgroundColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _scrollController.dispose();
    _roomIdController.dispose();
    _keywordController.dispose();
    _webSocketService.disconnect();
    super.dispose();
  }
}

// 更新数据模型
class LiveMessage {
  final String id;
  final User user;
  final String content;
  final DateTime timestamp;
  final MessageType type;

  LiveMessage({
    required this.user,
    required this.content,
    required this.timestamp,
    required this.type,
  }) : id = '${timestamp.millisecondsSinceEpoch}-${user.id}';

  factory LiveMessage.fromJson(Map<String, dynamic> json) {
    return LiveMessage(
      user: User.fromJson(json['user'] ?? {}),
      content: json['content'] ?? '',
      timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] ?? DateTime.now().millisecondsSinceEpoch),
      type: _parseMessageType(json['type'] ?? 'chat'), // 添加默认值
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'user': user.toJson(),
      'content': content,
      'timestamp': timestamp.millisecondsSinceEpoch,
      'type': type.toString().split('.').last,
    };
  }

  static MessageType _parseMessageType(String type) {
    switch (type) {
      case 'gift': return MessageType.gift;
      case 'like': return MessageType.like;
      case 'member': return MessageType.member;
      case 'social': return MessageType.social;
      default: return MessageType.chat;
    }
  }
}

class User {
  final String id;
  final String name;
  final String shortId;

  User({required this.id, required this.name, this.shortId = ''});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'] ?? 'unknown',
      name: json['name'] ?? '未知用户',
      shortId: json['short_id'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'short_id': shortId,
    };
  }
}

enum MessageType {
  chat,
  gift,
  like,
  member,
  social,
}